﻿Imports Twitterizer

Public Class TwitterAuth

    Public Shared Function Authenticate(ByVal forceRefresh As Boolean) As Boolean
        Dim result As Boolean = False

        If Not String.IsNullOrEmpty(My.Settings.OAuthToken) And Not String.IsNullOrEmpty(My.Settings.OAuthTokenSecret) And Not forceRefresh Then
            'User is already authenticated and access is allowed and a refresh hasn't been requested
            result = True
        Else

            If MessageBox.Show("TweetMyPC will now open Twitter in a new window where you have to allow access to your Twitter account so that TweetMyPC will be able to answer your tweets/commands securely." & vbCrLf & _
                            "You also need to copy the PIN which you will see after allowing TweetMyPC", "Secure Authorization", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) = DialogResult.OK Then
                Dim authorizationTokens = OAuthUtility.GetRequestToken(My.Resources.ConsumerKey, My.Resources.ConsumerSecret, "oob")
                Dim url As String = String.Format("http://twitter.com/oauth/authorize?oauth_token={0}", authorizationTokens.Token)
                System.Diagnostics.Process.Start(url)
                Dim pin = InputBox("Please enter the PIN which you got from Twitter:", "Enter PIN for Authorization")
                If Not String.IsNullOrEmpty(pin) Then
                    pin = pin.Trim()
                    Dim accessTokens = GetAccessToken(authorizationTokens.Token, pin)
                    If Not String.IsNullOrEmpty(accessTokens.Token) And Not String.IsNullOrEmpty(accessTokens.TokenSecret) Then
                        My.Settings.OAuthToken = accessTokens.Token
                        My.Settings.OAuthTokenSecret = accessTokens.TokenSecret
                        result = True
                    End If
                End If
            End If
        End If


        Return result
    End Function

    Public Shared Function GetOAuthTokens() As OAuthTokens
        Return New OAuthTokens With {
            .ConsumerKey = My.Resources.ConsumerKey,
            .ConsumerSecret = My.Resources.ConsumerSecret,
            .AccessToken = My.Settings.OAuthToken,
            .AccessTokenSecret = My.Settings.OAuthTokenSecret}
    End Function

    Private Shared Function GetRequestToken() As OAuthTokenResponse
        Return OAuthUtility.GetRequestToken(My.Resources.ConsumerKey, My.Resources.ConsumerSecret, "oob")
    End Function

    Private Shared Function GetAccessToken(ByVal token As String, ByVal pin As String) As OAuthTokenResponse
        Return OAuthUtility.GetAccessToken(My.Resources.ConsumerKey, My.Resources.ConsumerSecret, token, pin)
    End Function

End Class
